package com.intxt.bbs.controller;

import com.intxt.bbs.model.*;
import com.intxt.bbs.service.LinkService;
import com.intxt.bbs.util.Const;
import com.intxt.bbs.util.SimpleUtil;
import com.jfinal.core.Controller;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 帖子主要控制类
 *
 * @author Administrator
 */
public class TopicController extends Controller {

    private static final LinkService USER_LINK_SERVICE = new LinkService();
    private Logger log = Logger.getLogger(TopicController.class);

    /**
     * 帖子列表
     */
    public void index() {
        log.debug("----> 进入帖子列表index <----");
        List<Link> links = USER_LINK_SERVICE.findSystemLink();
        getSession().setAttribute("systemLinks", links);
        checkUserLinks();

        Integer gotoPage = getParaToInt("pageVal");
        log.debug("pageVal:" + gotoPage);
        if (gotoPage == null) {
            gotoPage = 1;
        }
        getTopicInfo(gotoPage);

        getAreaInfo();

        render("/topic/list.jsp");
    }

    /**
     * 获得帖子信息
     *
     * @param gotoPage 当前页
     */
    private void getTopicInfo(Integer gotoPage) {
        Page<Topic> pageInfo = Topic.DAO.paginate(gotoPage, Const.PAGE_SIZE, "select topic.id,topic.title,topic.publish_date,user.id as uid,user.username,user.head_img_address,area.area_name,label.weight as d", "from intxt_topic topic left join intxt_topic_label_ref ref\n" +
                "on topic.id = ref.topic_id  left join intxt_label label\n" +
                "on ref.label_id = label.id ,intxt_user user ,intxt_area area\n" +
                "where area.id = topic.area_id\n" +
                "group by topic.id order by d desc , topic.publish_date desc\n");
        List<Topic> list = pageInfo.getList();
        for (Topic t : list) {
            Integer labelId = t.get("d");

            String tid = t.getStr("id");
            if (null != labelId) {
                log.debug("tid:" + tid);
                String labelSQL = "select label.id,label.topic_label from intxt_label label,intxt_topic_label_ref ref where ref.topic_id = '" + tid + "' and label.id = ref.label_id order by label.weight desc";
                log.debug("labelSQL:" + labelSQL);
                List<TopicLabel> labels = TopicLabel.DAO.find(labelSQL);
                t.put("labels", labels);
            }
            String replyCountSQL = "select count(id) as count from intxt_reply reply where reply.topic_id = ? ";
            log.debug("labelSQL:" + replyCountSQL);
            Record replyCount = Db.findFirst(replyCountSQL, tid);
            t.put("replyCount", replyCount.get("count"));
            formateDate(t, "publish_date");
        }
        setAttr("pageInfo", pageInfo);
        setAttr("gotoPage", gotoPage);
        setAttr("topics", list);
    }

    /**
     * 获取版区信息
     */
    private void getAreaInfo() {
        String areaSql = "select area.id,area.area_name,count(topic.id) as n,user.username from test.intxt_area area ,test.intxt_topic topic ,test.intxt_user user where area.id = topic.area_id and area.master_id = user.id group by topic.area_id order by n desc";
        List<Area> areas = Area.DAO.find(areaSql);
        setAttr("areas", areas);
    }

    /**
     * 帖子详情
     */
    public void detail() {
        log.debug("--->进入帖子详情---->");
        String topicId = getPara("topicId");
        Integer gotoPage = getParaToInt("pageVal");
        String sql = "select topic.*,user.id as uid,user.username,user.head_img_address,area.area_name from intxt_topic topic, intxt_user user,intxt_area area where topic.publisher_id=user.id and topic.id=? and area.id = topic.area_id order by publish_date desc";

        Topic t = Topic.DAO.findFirst(sql, topicId);


        String labelSQL = "select label.id,label.topic_label from intxt_label label,intxt_topic_label_ref ref where ref.topic_id = '" + t.getStr("id") + "' and label.id = ref.label_id order by label.weight desc";
        log.debug("labelSQL:" + labelSQL);
        List<TopicLabel> labels = TopicLabel.DAO.find(labelSQL);
        t.put("labels", labels);


        formateDate(t, "publish_date");
        setAttr("topic", t);

        if (gotoPage == null) {
            gotoPage = 1;
        }
        setAttr("gotoPage", gotoPage);

        Page<Reply> replys = Reply.DAO.paginate(gotoPage, Reply.REPLY_PAGESIZE, "select reply.*,user.head_img_address", "from intxt_reply reply , intxt_user user where reply.user_id = user.id and topic_id = '" + topicId + "' order by reply_time desc");
        if (replys.getList().size() > 0) {
            setAttr("replys", replys);
        }

        getAreaInfo();

        checkUserLinks();
        render("/topic/detail.jsp");
    }

    /**
     * 发表主题
     */
    public void sendTopic() {
        String topicTitle = getPara("title"); //帖子主题
        String topicContent = getPara("content"); //帖子内容
        String areaId = getPara("areaId"); //帖子所在版区
        User u = (User) getSession().getAttribute("user"); //发帖人
        Topic topic = new Topic();
        topic.set("title", topicTitle);
        topic.set("content", topicContent);
        topic.set("publish_date", new Date());
        topic.set("publisher_id", u.getStr("id"));
        topic.set("state", "已发布");
        topic.set("area_id", areaId);
        UUID uuid = UUID.randomUUID();
        topic.set("id", uuid.toString());
        topic.save();
        redirect("/topic");
    }

    private void checkUserLinks() {
        User u = (User) getSession().getAttribute("user");
        if (u != null) {

            getSession().setAttribute("userLinks", USER_LINK_SERVICE.findUserLink(u.getStr("id")));
        }
    }

    public void send() {
        render("/topic/topic.jsp");
    }

	/*public void page(){
		log.debug("----> 进入帖子列表page <----");
		List<Link> links = USER_LINK_SERVICE.findSystemLink();
		getSession().setAttribute("systemLinks", links);
		checkUserLinks();
		
		String sql = "select topic.id,topic.title,topic.publish_date,user.id as uid,user.username,user.head_img_address from intxt_topic topic, intxt_user user where topic.publisher_id=user.id order by publish_date desc";
		
//		List<Topic> list = Topic.DAO.find("select * from "+TableMapping.me().getTable(Topic.class).getName());
//		List<Topic> list = Topic.DAO.find(sql);
//		for(Topic t : list){
//			formateDate(t);
//		}
		Integer gotoPage = getParaToInt("pageVal");
		log.debug("pageVal:"+gotoPage);
		if(gotoPage==null){
			gotoPage=1;
		}
        Page<Topic> pageInfo = Topic. DAO.paginate (gotoPage, 2, "select topic.id,topic.title,topic.publish_date,user.id as uid,user.username,user.head_img_address", "from intxt_topic topic, intxt_user user where topic.publisher_id=user.id order by publish_date desc") ;
        List<Topic> list = pageInfo.getList();
        for(Topic t : list){
        	formateDate(t);
        }
        setAttr("pageInfo", pageInfo);
        setAttr("gotoPage", gotoPage);
		setAttr("topics", list);
		render("/topic/list.jsp");
	}*/

    public void gotoReplyPage() {
        String topicId = getPara("topicId");
        int gotoPage = getParaToInt("gotoPage");

        Page<Reply> replyPage = Reply.DAO.paginate(gotoPage, Reply.REPLY_PAGESIZE, "select reply.*,user.head_img_address", "from intxt_reply reply , intxt_user user where reply.user_id = user.id and topic_id = '" + topicId + "' order by reply_time desc");

    }


    /**
     * 获取的时间格式不对 , 获取USER的时候处理一下
     *
     * @param m
     * @param args
     */
    private void formateDate(Model m, String args) {
        Date publish_date = m.getDate(args);
        try {
            m.set(args, SimpleUtil.formateDateTime(publish_date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

}
